# -*- coding: utf-8 -*-
__author__ = 'shijin'

import sys
import base64
from Crypto.Cipher import AES
import traceback

import logging

logging.basicConfig(filename='secret.log',
                    format='%(asctime)s -%(name)s-%(levelname)s-%(module)s.%(funcName)s:%(lineno)d:%(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S %p',
                    level=logging.DEBUG)

SKEY = 'ZAQ!2wsxQWERfdsa'


def encode_base64(string):
    try:
        string_base64 = base64.b64encode(string.encode(encoding='utf-8')).decode(encoding='utf-8')
        return string_base64
    except:
        logging.error("encode_base64 error: {e}".format(e=traceback.format_exc()))


def decode_base64(string_base64):
    try:
        string = base64.b64decode(string_base64).decode(encoding='utf-8')
        return string
    except:
        logging.error("decode_base64 error: {e}".format(e=traceback.format_exc()))


def add_to_16(string):
    """ 补充\0 """
    while len(string) % 16 != 0:
        string += '\0'
    return str.encode(string)  # 返回bytes


def encrypted_text(text):
    """ 加密 """
    aes = AES.new(str.encode(SKEY), AES.MODE_ECB)  # 初始化加密器，本例采用ECB加密模式
    encrypted_text = str(base64.encodebytes(aes.encrypt(add_to_16(text))), encoding='utf8').replace('\n', '')
    return encrypted_text


def decrypted_text(key):
    """ 解密 """
    aes = AES.new(str.encode(SKEY), AES.MODE_ECB)  # 初始化加密器，本例采用ECB加密模式
    decrypted_text = str(aes.decrypt(base64.decodebytes(bytes(key, encoding='utf8'))).rstrip(b'\0').decode("utf8"))
    return decrypted_text
